package com.example.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.domain.BorrowRecord;
import com.example.domain.Punishment;
import com.example.service.BorrowService;
import com.example.service.PunishmentService;
import com.example.service.UserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class RedisKeyExpirationListener implements MessageListener {

    @Resource
    private BorrowService borrowService;

    @Resource
    private PunishmentService punishmentService;

    @Resource
    private UserService userService;

    private final RedisSerializer<String> serializer = new StringRedisSerializer();

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String expiredKey = serializer.deserialize(message.getBody());
        log.info("Redis expired key: {}", expiredKey);

//         判断是否为借书记录的key（可以根据key的格式来判断）
        if (expiredKey != null && expiredKey.contains("borrowBook")) {
            // 解析出书籍ID和用户ID
            String[] parts = expiredKey.split(":");
            if (parts.length >= 3) {
                String userId = parts[1];
                String bookId = parts[2];
                // 假设没还书
//                log.info("User {} has not returned book {} in time.", userId, bookId);
                // 以防，查一下借书记录
                BorrowRecord borrowRecord = borrowService.getOne(new QueryWrapper<BorrowRecord>().eq("user_id", userId).eq("book_copy_id", bookId));
                if(borrowRecord!= null && borrowRecord.getActualReturnTime() == null){
                    // 用户未还书，处罚
                    log.info("用户{}未还书{}，处罚！", userId, bookId);
                    // 调用处罚接口
                    Punishment punishment = new Punishment();
                    punishment.setUserId(Long.parseLong(userId));
                    punishment.setPunishmentType(1);
                    punishment.setRelatedRecordId(borrowRecord.getId());
                    punishment.setReason("未还书，添加处罚");
                    punishment.setPunishmentStatus(0);
                    punishmentService.addPunishment(punishment);
                    log.info("用户{}已被处罚！", userId);
                    // 用户借书功能禁用
                    userService.disableBorrow(Long.parseLong(userId));
                }
            }
        }
    }
}